import WeCropper from '../we-cropper/we-cropper.js'

const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth // 示例为一个与屏幕等宽的正方形裁剪框
const height = width
const tftWidth = 240
const tftHeight = 240

const canvasId = 'cropper'
const ctx = wx.createCanvasContext(canvasId)
const cameraContext = wx.createCameraContext()

Page({
  data: {
    sendText: '成都碧富美特科技有限',
    fontColor: '#ff00ff',
    fontSize: 100,
    showScan: false,
    showLook: false,
    cropperOpt: {
      id: canvasId,
      width,  // 画布宽度
      height, // 画布高度
      scale: 2, // 最大缩放倍数
      zoom: 8, // 缩放系数
      cut: {
        x: (width - tftWidth) / 2, // 裁剪框x轴起点
        y: (width - tftHeight) / 2, // 裁剪框y轴期起点
        width: tftWidth, // 裁剪框宽度
        height: tftHeight // 裁剪框高度
      }
    }
  },

  onLoad() {
    const { cropperOpt } = this.data
    // 若同一个页面只有一个裁剪容器，在其它Page方法中可通过this.wecropper访问实例
    new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context: ${ctx}`)
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context: ${ctx}`)
        wx.hideToast()
      })   
  },
  uploadTap() {
    this.closeLook()
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        self.wecropper.pushOrign(src)
      }
    })
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },

  
  showScan() {
    this.closeLook()
    this.setData({ showScan: true })
    wx.redirectTo({
      url: '/scan/scan?id=1'
    })
  },
  cancelScan() {
    this.setData({ showScan: false })
  },
  showLook() {
    this.setData({ showLook: !this.data.showLook })
  },
  closeLook() {
    this.setData({ showLook: false })
  },
  linkDevice() {

  },
  sendBle() {
    this.closeLook()
    let self = this
    wx.canvasGetImageData({
      canvasId: canvasId,
      x: (width - tftWidth) / 2,
      y: (width - tftHeight) / 2,
      width: tftWidth,
      height: tftHeight,
      success(res) {
        // 数据转换
        let buffer = self.convertRGB(res.data)
        debugger
      }
    })
  },
  inputChange: function (e) {
    var val = e.detail.value;
    this.setData({
      sendText: val
    });
  },
  sendText() {
    this.closeLook()
    let length = this.data.sendText.length
    if(length == 0) {
      console.warn('无数据发送')
    }
    // 单行显示字数
    let rowNum = parseInt(tftWidth / this.data.fontSize)
    // 显示页数 胸牌滚屏实现
    let pages = length % rowNum == 0 ? parseInt(length / rowNum) : parseInt(length / rowNum) + 1
    let currText; // 当前页显示文字
    let yPos = height / 2 + this.data.fontSize / 2
    let xPosBegin = (width - tftWidth) / 2
    for(let i = 0; i < pages; i ++) {
      ctx.setFillStyle(this.data.fontColor)
      // ctx.clearRect(0, 0, width, width)
      // 将文字显示在屏幕上
      ctx.setFontSize(this.data.fontSize)
      // 最后一页
      if (i == (pages - 1) && length % rowNum != 0) {
        currText = this.data.sendText.substring(rowNum * i, length)
      }else {
        currText = this.data.sendText.substring(rowNum * i, rowNum * i + rowNum)
      }
      for (let j = 0; j < currText.length; j ++) {
        ctx.fillText(currText.charAt(j), xPosBegin + j * this.data.fontSize, yPos)
      }
      console.log("begin send text:" + currText)
      ctx.draw()
    }
  },
  convertRGB(data) {
    // 数据转换
    let buffer = new ArrayBuffer(tftWidth * tftHeight * 2)
    let dataView = new DataView(buffer)
    let uint16
    let rVal, gVal, bVal
    let index = 0
    for(let i = 0; i<data.length; i += 4) {
      rVal = data[i] / 8 << 11
      gVal = data[i + 1] / 4 << 5
      bVal = data[i + 2] / 8
      uint16 = rVal & gVal & bVal
      dataView.setUint8(index, (uint16 & 0xff00) >> 8)
      dataView.setUint8(index + 1, uint16 & 0x00ff)
      index += 2
    }
    return buffer
  }
})